import time
import random
import arrow, datetime
import numpy as np
import pickle, os
from common.conf.config import Conf
import json
from pymongo import MongoClient
import time

import pymongo
import time
import datetime
from bson.objectid import ObjectId


class ToolTime:

    def is_date(self, s):
        try:
            arrow.get(s)
            return True
        except:
            return False

    def is_percent(self, v):
        try:
            d = float(v)
            if 0 <= d <= 100:
                return True
        except:
            pass
        return False

    def is_float(self, v):
        try:
            d = float(v)
            return True
        except:
            pass
        return False

    def is_int(self, v):
        try:
            d = int(v)
            return True
        except:
            pass
        return False

    def year(self, s):
        t = arrow.get(s)
        return t.year

    def date(self, s):
        l = s.split("-")
        d = l[-1]
        return int(d)

    def month(self, s):

        t = arrow.get(s)
        return t.month

    def weekday(self, s):
        a = datetime.date(self.year(s), self.month(s), self.date(s))
        return a.isoweekday()

    @property
    def yesterday(self):
        n = arrow.now("Asia/Shanghai").now()
        y = n.shift(days=-1)
        return y.format()[:10]

    @property
    def today(self):
        return arrow.now("Asia/Shanghai").format()[:10]

    @property
    def now2minute(self):
        return arrow.now("Asia/Shanghai").format()[:16]

    @property
    def now2second(self):
        return arrow.now("Asia/Shanghai").format()[:19]

    @property
    def today_dir(self):
        return f"{Conf().cache}/{self.today}"

    def week_of_year(self, s):
        a = datetime.date(self.year(s), self.month(s), self.date(s)).isocalendar()
        return a[1]

    def week_of_month(self, s):
        week = self.week_of_year(s)
        begin = f"{s[:-3]}-01"
        week1 = self.week_of_year(begin)
        return week - week1 + 1

    def add_zero(self, m):
        m = int(m)
        if m < 10: return f"0{m}"
        return f"{m}"

    def convert_date(self, s):
        try:
            d = arrow.get(s)
            s = d.format()[:10]
            return s
        except Exception as e:
            return ""
    def last_n_month(self, n):
        month = self.month(self.today)
        year = self.year(self.today)
        if month > n:
            y = year
            m = month - n
        else:
            y = year - 1
            m = month + 12 - n
        m=m if m>=10 else f"0{m}"
        return f"{y}-{m}"
    def last_n_month_with_month(self, n,month):
        s=f"{month}-01"
        month = self.month(s)
        year = self.year(s)
        if month > n:
            y = year
            m = month - n
        else:
            y = year - 1
            m = month + 12 - n
        m = m if m >= 10 else f"0{m}"
        return f"{y}-{m}"





    def next_month(self, year, month):
        m = int(month)
        y = int(year)
        if m == 12:
            m = 1
            y = y + 1
        else:
            m = m + 1
        return y, m

    def month_end(self, year, month):
        y, m = self.next_month(year, month)
        begin = arrow.get(f"{y}-{m}-01")
        end = begin.shift(days=-1)
        e = end.format()[:10]
        return e

    def differ_days(self, s1, s2):
        t1 = arrow.get(s1)
        t2 = arrow.get(s2)
        differ = t1 - t2
        d = differ.days
        return abs(d)

    def feilv(self, value, formula):
        v = float(value) / 100
        if "*" in formula:
            f = formula.replace("*", "")
            v = v * float(f)
        if "+" in formula:
            f = formula.replace("+", "")
            v = v + float(f)
        if "-" in formula:
            f = formula.replace("-", "")
            v = v - float(f)
        return v

    def save_pickle(self, path, data):
        with open(path, 'wb') as fh:
            pickle.dump(data, fh)

    def read_pickle(self, path):
        if os.path.exists(path):
            pickle_off = open(path, "rb")
            emp = pickle.load(pickle_off)
            return emp
        return None

    def how_many_week_before(self, today, before):
        this_weekday = self.weekday(today)
        this_monday = arrow.get(today).shift(days=1 - this_weekday)
        bf = arrow.get(before)
        differ = this_monday - bf
        days = differ.days
        if days <= 0:
            days = 0
        else:
            days = days + 6
        return int(days / 7)

    def conf_2_date_this_m(self, d):
        s = self.today
        if d == "月末":
            end = self.month_end(self.year(s), self.month(s))
            return end
        else:
            m = s[:7]
            end = arrow.get(f"{m}-{d}").format()[:10]
            return end

    def days_to_month1st(self):
        m = self.today[:7]
        return self.differ_days(f"{m}-01", self.today)

    def object_id2time(self, object_id):
        object_id = str(object_id)
        timeStamp = int(object_id[:8], 16)
        s = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timeStamp))
        a = arrow.get(s).shift(hours=-8).format()[:19]
        return a

    def object_id_from_time(self):
        from_datetime = datetime.datetime.now()
        print("产生id的时间戳=========", from_datetime)
        oid = ObjectId.from_datetime(generation_time=from_datetime)
        ts = str(oid)[:8]
        back = [str(random.randint(0, 9)) for i in range(16)]
        back = "".join(back)
        res = ts + back
        oid = ObjectId(res)
        return oid


if __name__ == '__main__':
    t = ToolTime()
    m1_before =t.last_n_month(0)
    d = t.date(t.today)
    m1 = f"{m1_before}-{d}"
    print (m1)
